package me.caofeng.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.util
 * @Description: MD5工具
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-16 17:07
 * @Version: V1.0
 */
public class MD5Util {
    private static final String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    private static Logger LOGGER = LogManager.getLogger(MD5Util.class);
    /**
     * 加密盐值,请勿修改
     */
    private final static String SALT = "2327edd7035e469ea2939f60a20fba68df37a68a30134e1c9c973c6daf90d5ab";

    private static String byteArrayToHexString(byte[] bytes) {
        StringBuffer buffer = new StringBuffer();
        for (byte b : bytes) {
            buffer.append(byteToHexString(b));
        }
        return buffer.toString();

    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0) {
            n = n + 256;
        }

        int d1 = n / 16;
        int d2 = n % 16;

        return hexDigits[d1] + hexDigits[d2];
    }

    private static String MD5Encode(String origin, String charsetName) {
        String md5 = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            if (CheckUtil.isEmpty(charsetName)) {
                md5 = byteArrayToHexString(messageDigest.digest(origin.getBytes()));
            } else {
                md5 = byteArrayToHexString(messageDigest.digest(origin.getBytes(charsetName)));
            }
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error(e);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e);
        }

        return md5.toUpperCase();
    }

    public static String Utf8Md5Encode(String origin) {
        return MD5Encode(origin + SALT, "utf-8");
    }


    /**
     * @Author:曹峰 blog.caofeng.me
     * @Date: 2017/6/18 17:31
     * @Description:  生成4位数的随机验证码
    */
    public static String generaVerifyCode() {
        int random = (int) (Math.random() * (9999 - 1000 + 1) + 1000);
        return String.valueOf(random);
    }



}
